package com.atguigu.chapter07.timer;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/7/20 10:36
 */
public class Flink02_Timeer_Project {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        SingleOutputStreamOperator<WaterSensor> stream = env
            .socketTextStream("hadoop162", 9999)  // 在socket终端只输入毫秒级别的时间戳
            .map(value -> {
                String[] datas = value.split(",");
                return new WaterSensor(datas[0], Long.valueOf(datas[1]), Integer.valueOf(datas[2]));
                
            });
        
        WatermarkStrategy<WaterSensor> wms = WatermarkStrategy
            .<WaterSensor>forMonotonousTimestamps()
            .withTimestampAssigner((element, recordTimestamp) -> element.getTs() * 1000);
        
        stream
            .assignTimestampsAndWatermarks(wms)
            .keyBy(WaterSensor::getId)
            .process(new KeyedProcessFunction<String, WaterSensor, String>() {
                private long timerTs;
                boolean isFirst = true;
                int lastVc;
                
                @Override
                public void processElement(WaterSensor value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    /*
                    1. 第一条数据来了之后, 注册一个5秒后触发的定时器
                    2. 下一条数据来了之后, 判断与上一条的大小关系
                    3. 如果大于等于上一条, 不用管
                    4. 如果小于上一条则删除定时器
                   
                    
                    5. 定时器如果触发, 重新注册一个新的定时器
                     */
                    if (isFirst) {
                        // 注册定时器
                        timerTs = ctx.timestamp() + 5000;
                        ctx.timerService().registerEventTimeTimer(timerTs);
                        
                        isFirst = false;
                    } else {
                        // 判断与上次的水位的比较
                        if (value.getVc() < lastVc) { // 水位下降
                            // 删除定时器
                            ctx.timerService().deleteEventTimeTimer(timerTs);
                            
                            // 当定时器被删之后,需要重新注册一个新的定时器
                            timerTs = ctx.timestamp() + 5000;
                            ctx.timerService().registerEventTimeTimer(timerTs);
                            
                        } else {
                            System.out.println("水位上升或者不变");
                        }
                    }
                    lastVc = value.getVc();
                    
                }
    
                @Override
                public void onTimer(long timestamp,
                                    OnTimerContext ctx,
                                    Collector<String> out) throws Exception {
                    out.collect(ctx.getCurrentKey() + " 在5s内水位连续上升, 发出红色预警");
                    isFirst = true;
                }
            })
            .print();
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
}
